package com.yang.leather.mall.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

public class MallControlFilter implements Filter{
	private static Map<String,String[]> availableLocal = new HashMap<String,String[]>();
	
	static{
		availableLocal.put("zh", new String[]{"zh","CN"});
		availableLocal.put("en", new String[]{"en","US"});
	}

	public void destroy() {
		
	}

	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)servletRequest;
		HttpSession session = request.getSession();
		
		String local = request.getParameter("local");
		String sessionLocal = (String)session.getAttribute("language");
		if(!(StringUtils.isNotEmpty(local) && availableLocal.containsKey(local.toLowerCase()))
				&& StringUtils.isEmpty(sessionLocal)){
			local = "zh";
		}
		
		if(StringUtils.isNotEmpty(local) && !local.equals(sessionLocal)){
			Locale locale = new Locale(availableLocal.get(local)[0],availableLocal.get(local)[1]);
			request.getSession().setAttribute("WW_TRANS_I18N_LOCALE", locale);
			request.getSession().setAttribute("language", local);
		}
		request.setAttribute("language", StringUtils.isNotEmpty(local) ? local : sessionLocal);
		
		chain.doFilter(servletRequest, servletResponse);
	}

	public void init(FilterConfig arg0) throws ServletException {
		
	}

}
